package com.googlecode.lazyrecords.berkeleydb;

import com.googlecode.totallylazy.Function1;
import com.googlecode.totallylazy.Option;
import com.sleepycat.je.Environment;
import com.sleepycat.je.Transaction;
import com.sleepycat.je.TransactionConfig;

public class JeTransaction implements com.googlecode.lazyrecords.Transaction {
    private final Transaction transaction;

    public JeTransaction(Environment environment) {
        TransactionConfig config = new TransactionConfig();
        transaction = environment.beginTransaction(null, config);
    }

    static Function1<JeTransaction, Transaction> transaction() {
        return new Function1<JeTransaction, Transaction>() {
            @Override
            public Transaction call(JeTransaction transaction) throws Exception {
                return transaction.transaction;
            }
        };
    }

    @Override
    public void commit() {
        transaction.commit();
    }

    @Override
    public void rollback() {
        transaction.abort();
    }

    static Transaction transaction(Option<JeTransaction> transaction) {
        return transaction.map(JeTransaction.transaction()).getOrNull();
    }
}
